#include "Players.h"
#include "KinectManager.h"
//#include "Matting.h"
ifstream Rin("KC_Result.txt");
Players::Players(QVector2D position,QVector2D scaleFactor,int deltaThreshold /* = 5 */)
{
	mPosition = position;
	mScaleFactor = scaleFactor;
	mDeltaThreshold = deltaThreshold;
	mTextureData = new unsigned char[ PLAYER_TEXTURE_WIDTH*PLAYER_TEXTURE_HEIGHT*3];
	//mMatting = new Matting();
}
Players::~Players()
{
	if (mTextureData)
	{
		delete []mTextureData;
		mTextureData = 0;
	}
	if (mMatting)
	{
		delete mMatting;
		mMatting = 0;
	}
}
void Players::Render()
{
	glBindTexture(GL_TEXTURE_2D,m_pTexture);
	glPushMatrix();
	glLoadIdentity();
	//glRotatef(180,0,0,1);
	glBegin(GL_QUADS);

	//glTexCoord2f( 1. / TILE_HEIGHT * PLAYER_TEXTURE_HEIGHT, 1);
	//glVertex2f( 0, 0 );

	//glTexCoord2f( 0, 1 );
	//glVertex2f( TILE_WIDTH, 0 );

	//glTexCoord2f( 0.f, 0 );
	//glVertex2f( TILE_WIDTH, TILE_HEIGHT );

	//glTexCoord2f( 1. / TILE_HEIGHT * PLAYER_TEXTURE_HEIGHT, 0 );
	//glVertex2f( 0, TILE_HEIGHT );

	glTexCoord2f( 1., 1);
	glVertex2f( 0, 0 );

	glTexCoord2f( 0, 1 );
	glVertex2f( 1.f * PLAYER_TEXTURE_WIDTH / PLAYER_TEXTURE_HEIGHT * TILE_HEIGHT, 0 );

	glTexCoord2f( 0.f, 0 );
	glVertex2f( 1.f * PLAYER_TEXTURE_WIDTH / PLAYER_TEXTURE_HEIGHT * TILE_HEIGHT, TILE_HEIGHT );

	glTexCoord2f( 1. , 0 );
	glVertex2f( 0, TILE_HEIGHT );

	//glTexCoord2f( 0, 1);
	//glVertex2f( 0, 0 );

	//glTexCoord2f( 1. / TILE_HEIGHT * PLAYER_TEXTURE_HEIGHT, 1 );
	//glVertex2f( TILE_WIDTH, 0 );

	//glTexCoord2f( 1. / TILE_HEIGHT * PLAYER_TEXTURE_HEIGHT, 0 );
	//glVertex2f( TILE_WIDTH, TILE_HEIGHT );

	//glTexCoord2f( 0, 0 );
	//glVertex2f( 0, TILE_HEIGHT );

	glEnd();
	glPopMatrix();
}
void Players::BindTexture()
{
	memset(mTextureData,0,PLAYER_TEXTURE_WIDTH*PLAYER_TEXTURE_HEIGHT*3);
	BYTE  *pSrc = KinectManager::getSingleton().GetPlayerTex();
	if (!pSrc)
	{
		return;
	}
	glBindTexture(GL_TEXTURE_2D,m_pTexture);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 640, 480, 0, GL_RGB, GL_UNSIGNED_BYTE,mTextureData); 
}
void Players::InitTexture()
{
	glGenTextures(1,&m_pTexture);
	glBindTexture(GL_TEXTURE_2D,m_pTexture);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
	glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
	ReadMatrixFromFile();
}
void Players::Update(float fElapsedTime)
{

}
void Players::ReadMatrixFromFile(){
	int index = 0;
	while(!Rin.eof())
	{
		double t;
		Rin>>t;
		matrixArray[index++]=t;
	}
}

void Players::UpdateTexture()
{
	memcpy(mTextureData, KinectManager::getSingleton().GetVideoDevice()->GetBufferData(),
		PLAYER_TEXTURE_WIDTH * PLAYER_TEXTURE_HEIGHT * 3);
	glBindTexture(GL_TEXTURE_2D,m_pTexture);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, PLAYER_TEXTURE_WIDTH, PLAYER_TEXTURE_HEIGHT, 0, 
		GL_RGB, GL_UNSIGNED_BYTE,mTextureData);
}